package com.cloud.file.controller;


import com.alibaba.fastjson.JSONObject;
import com.cloud.common.constants.SwggerCommonTags;
import com.cloud.common.response.SimpleResponse;
import com.cloud.common.syse.HttpCodeE;
import com.cloud.file.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName : OssController  //类名
 * @Description : oss回调控制层  //描述
 * @Author : JiangWenJie  //作者
 * @Date: 2021-02-05 15:08  //时间
 */
@Api(tags = SwggerCommonTags.SYS_FILE_MODULE)
@RestController
@RequestMapping("/api/oss")
public class OssController {

    @Autowired
    private OssService ossService;

    @ApiOperation(value = "oss文件上传回调接口", httpMethod = "POST")
    @RequestMapping(value = "callback",method= RequestMethod.POST)
    public void postCallback(@RequestBody String requestBody,
                             @RequestHeader("x-oss-pub-key-url") String pubKeyUrl,
                             @RequestHeader("Authorization") String authorization,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        SimpleResponse resp = ossService.handlerCallbackResult(requestBody, authorization, pubKeyUrl,
                request.getQueryString(), request.getRequestURI());
        if (resp.getCode() == HttpCodeE.调用成功.value) {
            response(request, response, JSONObject.toJSONString(resp), HttpServletResponse.SC_OK);
        } else {
            response(request, response, JSONObject.toJSONString(resp), HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    private void response(HttpServletRequest request, HttpServletResponse response, String results, int status)
            throws IOException {
        String callbackFunName = request.getParameter("callback");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        if (callbackFunName == null || callbackFunName.equalsIgnoreCase("")) {
            response.getWriter().println(results);
        } else {
            response.getWriter().println(callbackFunName + "( " + results + " )");
        }
        response.setStatus(status);
        response.flushBuffer();
    }
}
